package la.gs;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import la.common.CommonException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class GSConnector {
	
	private Log logger = LogFactory.getLog(this.getClass());
	
	/**
	 * @param criteria 
	 * @param startOffset may null for default
	 * @param maxRecord may null for default
	 * @return result
	 * @throws CommonException 
	 * 
	 */
	public CharSequence search(GSearchCriteria criteria, Integer startOffset, Integer maxRecord) throws CommonException {
		
		String url = "http://www.google.com/search?"
			+ "hl=en&ie=utf-8&oe=utf-8&start=startOffsetVal&num=maxRecordPerPageVal&as_filetype=fileTypeVal&q=keywordVal";
		String fileType = criteria.getFileType();		
		String keyword = criteria.getKeyword();
		try {
			if( startOffset == null ) {
				startOffset = 0;
			}
			if( maxRecord == null ) {
				maxRecord = 10;
			}
			url = url.replace("startOffsetVal", startOffset.toString());
			url = url.replace("maxRecordPerPageVal", maxRecord.toString());
			
			if( fileType == null ) {
				url = url.replace("as_filetype=fileTypeVal&", "");
			}
			else {
				url = url.replace("fileTypeVal", URLEncoder.encode(fileType, "utf-8"));
			}
			url = url.replace("keywordVal", URLEncoder.encode(keyword, "utf-8"));
		} catch (UnsupportedEncodingException e1) {
			throw new CommonException( e1 );
		}

		HttpClient client = new HttpClient();

		GetMethod method = new GetMethod(url);

		method.addRequestHeader("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
		method.addRequestHeader("Accept:", "image/png,*/*;q=0.5");
		method.addRequestHeader("Accept-Language", "en-us,en;q=0.5");

		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(0, false));

		try {
			logger.debug( "GSConnector:" + url );
			int statusCode = client.executeMethod(method);

			if (statusCode != HttpStatus.SC_OK) {
				throw new CommonException( "Method failed: " + method.getStatusLine() );
			}

			InputStream is = method.getResponseBodyAsStream();
			StringWriter sw = new StringWriter();
			
			IOUtils.copy(is, sw, "utf-8");
			
			return sw.toString();

		} catch (IOException e) {
			throw new CommonException( e );
		} finally {
			// Release the connection.
			method.releaseConnection();
		}
	}
}
